package cn.tedu.hospitalqd.service.impl;

import cn.tedu.hospitalqd.ex.ServiceException;
import cn.tedu.hospitalqd.mapper.InhospitalMapper;
import cn.tedu.hospitalqd.pojo.dto.InhospitalAddNewDTO;
import cn.tedu.hospitalqd.pojo.entity.Inhospital;
import cn.tedu.hospitalqd.service.InhospitalService;
import cn.tedu.hospitalqd.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class InhospitalServiceImpl implements InhospitalService {

    @Autowired
    private InhospitalMapper inhospitalMapper;

    @Override
    public void addNew(InhospitalAddNewDTO inhospitalAddNewDTO) {
        // 从参数对象中获取住院患者名称
        String name = inhospitalAddNewDTO.getPName(); ;
        // 调用inhospitalMapper的int countByName(String name)根据名称执行统计
        int countByName = inhospitalMapper.countByName(name);
        // 判断统计结果是否大于0
        if (countByName > 0) {
            // 是：抛出异常
            String message = "添加住院患者失败，该患者名字已存在！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Inhospital对象
        Inhospital inhospital = new Inhospital();
        // 调用BeanUtils.copyProperties()将参数对象的属性值复制到Inhospital对象中
        BeanUtils.copyProperties(inhospitalAddNewDTO, inhospital);
        // 调用inhospitalMapper的int insert(Inhospital inhospital)方法将住院患者数据插入到数据库
        int rows = inhospitalMapper.insert(inhospital);
        if (rows != 1) {
            String message = "添加住院患者失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }
}
